<template>
  <div>
    <ElCard style="margin-bottom: 10px; height: 80px">
      <ElForm inline style="display: flex; justify-content: space-between; align-items: center">
        <ElFormItem label="用户名:">
          <ElInput placeholder="请输入需要搜索用户名" v-model="seekUsername"> </ElInput>
        </ElFormItem>
        <ElFormItem>
          <el-button type="primary" size="default" @click="seek" :disabled="!seekUsername"
            >搜索</el-button
          >
          <el-button type="primary" size="default" @click="reset">重置</el-button>
        </ElFormItem>
      </ElForm>
    </ElCard>
    <ElCard>
      <div style="margin-bottom: 10px">
        <el-button type="primary" size="default" @click="addDrawer" v-has="'btn.User.add'">
          添加用户
        </el-button>
        <el-button
          v-has="'btn.User.remove'"
          type="primary"
          size="default"
          @click="selectDelUser"
          :disabled="selectArr.length ? false : true"
          >批量删除</el-button
        >
      </div>
      <ElTable border :data="UserArr" style="margin-bottom: 10px" @selection-change="selectChange">
        <ElTableColumn type="selection" align="center"> </ElTableColumn>
        <ElTableColumn type="index" label="#" align="center"> </ElTableColumn>
        <ElTableColumn type="" label="ID" align="center" prop="id"> </ElTableColumn>
        <ElTableColumn
          type=""
          label="用户名"
          align="center"
          prop="username"
          show-overflow-tooltip
        ></ElTableColumn>
        <ElTableColumn type="" label="用户昵称" align="center" prop="name" show-overflow-tooltip>
        </ElTableColumn>
        <ElTableColumn
          type=""
          label="用户角色"
          align="center"
          prop="roleName"
          show-overflow-tooltip
        >
        </ElTableColumn>
        <ElTableColumn
          type=""
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        >
        </ElTableColumn>
        <ElTableColumn
          type=""
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        >
        </ElTableColumn>
        <ElTableColumn label="操作" align="center" width="300px">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="user"
              @click="ChangeDrawer(row)"
              v-has="'btn.User.assgin'"
              >分配角色</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="edit"
              @click="updataDrawer(row)"
              v-has="'btn.User.update'"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="Delete"
              @click="delUser(row)"
              v-has="'btn.User.remove'"
              >删除</el-button
            >
          </template>
        </ElTableColumn>
      </ElTable>
      <div>
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="limit"
          :page-sizes="[5, 7, 9, 11]"
          layout="  prev, pager, next, jumper , -> , sizes , total"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </ElCard>
    <el-drawer v-model="drawer1" title="分配角色(职位)" size="30%">
      <div>
        <ElForm>
          <ElFormItem label="用户姓名">
            <ElInput v-model="UserParams.username" :disabled="true"> </ElInput>
          </ElFormItem>
          <ElFormItem label="职位列表">
            <div>
              <el-checkbox
                label="全选"
                :indeterminate="indeterminate"
                v-model="checkAll"
                @change="handleCheckAllChange"
              >
              </el-checkbox>
              <el-checkbox-group v-model="userRoles" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="(i, index) in allRolesList" :key="index" :label="i">
                  {{ i.roleName }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </ElFormItem>
        </ElForm>
      </div>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer1 = false">取消</el-button>
          <el-button type="primary" @click="UpdataUserRolesOK">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="drawer" :title="UserParams.id ? '修改用户' : '添加用户'" size="30%">
      <div>
        <ElForm :model="UserParams" ref="formRef" :rules="rule">
          <ElFormItem label="用户名" prop="username" label-width="80px">
            <ElInput placeholder="请输入用户名" v-model="UserParams.username"> </ElInput>
          </ElFormItem>
          <ElFormItem label="用户昵称" label-width="80px" prop="name">
            <ElInput placeholder="请输入用户昵称" v-model="UserParams.name"> </ElInput>
          </ElFormItem>
          <ElFormItem label="用户密码" label-width="80px" prop="password" v-if="!UserParams.id">
            <ElInput placeholder="请输入用户密码" v-model="UserParams.password"> </ElInput>
          </ElFormItem>
        </ElForm>
      </div>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancalUser">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup name="User">
import {
  reqDelUser,
  reqHasAdminData,
  reqSaveAdminRoles,
  reqSaveUser,
  reqSelectIdDelUser,
  reqUpdataUser,
  reqUserList
} from '@/API/acl/user'
import { AssignRoleData, RecordData, roleVo, User } from '@/API/acl/user/type'
import { ElCheckbox, ElCheckboxGroup, FormRules } from 'element-plus'
import { nextTick, onMounted, reactive, ref } from 'vue'
let checkAll = ref(false)
let indeterminate = ref(false)
let total = ref<Number | String>(0)
/*  limit 页数
    page  页码 */
let limit = ref(5)
let page = ref(1)
let drawer = ref(false)
let drawer1 = ref(false)
let seekUsername = ref('')
let formRef = ref()
let UserArr = ref<RecordData>([
  {
    id: '',
    createTime: '',
    updateTime: '',
    username: '',
    password: '',
    name: ''
  }
])
let UserParams = ref<User>({
  username: '',
  name: '',
  password: ''
})
let userRoles = ref<AssignRoleData>([])
let allRolesList = ref<AssignRoleData>([])
let selectArr = ref([])
const reset = () => {
  seekUsername.value = ''
  getUserList()
}
/* 每次多选框变化后的事件 */
const selectChange = (val) => {
  selectArr.value = val
}
const UpdataUserRolesOK = async () => {
  /* 整理数据 */
  let roleVo: roleVo = {
    roleIdList: userRoles.value.map((item) => {
      return item.id
    }),
    userId: UserParams.value.id
  }
  let result = await reqSaveAdminRoles(roleVo)
  if (result.code == 200) {
    getUserList()
    drawer1.value = false
  }
}
const handleCheckedCitiesChange = (value) => {
  const checkedLength = value.length
  checkAll.value = checkedLength === allRolesList.value.length
  indeterminate.value = checkedLength > 0 && checkedLength < allRolesList.value.length
}
const handleCheckAllChange = (val) => {
  userRoles.value = val ? allRolesList.value : []
  indeterminate.value = false
}
const delUser = async (row) => {
  ElMessageBox.confirm('确定删除用户数据吗?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let result = await reqDelUser(row.id)
      if (result.code == 200) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        getUserList()
      } else {
        console.log(result.message)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消'
      })
    })
}
const saveUser = async () => {
  await formRef.value.validate()
  let result
  UserParams.value.id
    ? (result = await reqUpdataUser(UserParams.value))
    : (result = await reqSaveUser(UserParams.value))
  if (result.code == 200) {
    getUserList()
    drawer.value = false
  } else {
    console.log(result.message)
  }
}
const cancalUser = () => {
  drawer.value = false
}
const seek = () => {
  getUserList()
  seekUsername.value = ''
}
const selectDelUser = async () => {
  ElMessageBox.confirm('确定批量删除用户数据吗?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let idList = selectArr.value.map((i) => {
        return i.id
      })
      let result = await reqSelectIdDelUser(idList)
      if (result.code == 200) {
        page.value = 1
        getUserList()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消'
      })
    })
}
const ChangeDrawer = async (row) => {
  Object.assign(UserParams.value, row)
  let result = await reqHasAdminData(UserParams.value.id)
  if (result.code == 200) {
    userRoles.value = result.data.assignRoles
    allRolesList.value = result.data.allRolesList
    drawer1.value = true
  } else {
    console.log(result.message)
  }
}
const addDrawer = () => {
  console.log('执行了')

  drawer.value = true
  /* 重置 */
  Object.assign(UserParams.value, {
    id: 0,
    username: '',
    name: '',
    password: ''
  })
  nextTick(() => {
    formRef.value.resetFields()
  })
}
/*  直接赋值与对象的assign方法与深复制的区别
直接复制,会导致我们要临时使用数据的内存地址同时指向我们显示的数据从而出现bug,在我们使用某种办法,清空临时使用的数据的时候,会导致bug出现,原来要显示的数据因为数据存储内存地址是一致的,从而导致显示的
数据也被清空,出现bug.数据与实际的数据是不同的'
而Object.assign方法虽然也是浅复制.但是可以赋值一个成新的对象,第一层对象的内存地址是新的.但其第二层第三层的对象数组等等数据是采用引用的方式去赋值的.也会导致修改数据后的内存地址一致从而发生数据变化.
*/
const updataDrawer = (row: User) => {
  Object.assign(UserParams.value, row)
  drawer.value = true
}
/* 当我们的当前显示的页数发生变化时 */
const handleSizeChange = () => {
  getUserList()
}
/* 当页码发生变化时 */
const handleCurrentChange = () => {
  getUserList()
}
/* 获取用户管理列表数据 */
const getUserList = async () => {
  let result = await reqUserList(page.value, limit.value, seekUsername?.value)
  if (result.code == 200) {
    UserArr.value = result.data.records
    total.value = result.data.total
  } else {
    console.log(result.message)
  }
}
/* 表单验证的模式 rule是其规则对象本身,value为值,cb回调什么都不输入就放行.*/
const nameRule = (rule, value, cb) => {
  if (!value) {
    cb(new Error('不能为空值'))
  } else if (value.replace(/\s+/g, '').length < 5) {
    cb(new Error('少于5个字符串'))
  } else {
    cb()
  }
}
const numberRule = (rule, value, cb) => {
  if (!value) {
    cb(new Error('不能为空值'))
  } else {
    if (value.replace(/\s+/g, '').length < 6) {
      cb(new Error('少于6个字符串'))
    } else {
      cb()
    }
  }
}
let rule = reactive<FormRules>({
  username: [
    {
      validator: nameRule,
      required: true,
      message: '不能少于5个字符',
      trigger: 'blur'
    }
  ],
  name: [
    {
      validator: nameRule,
      required: true,
      message: '不能少于5个字符',
      trigger: 'blur'
    }
  ],
  password: [
    {
      validator: numberRule,
      required: true,
      message: '不能少于6个字符',
      trigger: 'blur'
    }
  ]
})

onMounted(() => {
  getUserList()
})
</script>

<style scoped></style>
